package net.butfly.bus.util;

import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;

import net.butfly.albacore.utils.UtilsBase;
import net.butfly.bus.TX;

public class TXUtils extends UtilsBase {
	public static final TX TXImpl(final String tx) {
		return TXImpl(tx, TX.INIT_VERSION);
	}

	public static final TX TXImpl(final TX tx) {
		return TXImpl(tx.value(), tx.version());
	}

	public static TX TXImpl(final String code, final String version) {
		String key = key(code, version);
		if (TX_IMPL_POOL.containsKey(key))
			return TX_IMPL_POOL.get(key);
		TX impl = new TXImpl(code, version);
		TX_IMPL_POOL.put(key, impl);
		return impl;
	}

	public static class TXImpl implements TX, Serializable {
		private static final long serialVersionUID = 2457478261818103564L;

		public TXImpl(String code, String version) {
			super();
			this.code = code;
			this.version = version;
		}

		public TXImpl(String key) {
			String[] keys = key.split(":");
			if (keys.length != 2)
				throw new IllegalArgumentException();
			this.code = keys[0];
			this.version = keys[1];
		}

		private String code;
		private String version;

		@Override
		public Class<? extends Annotation> annotationType() {
			return TX.class;
		}

		@Override
		public String value() {
			return code;
		}

		@Override
		public String version() {
			return version;
		}

		@Override
		public String toString() {
			return key(code, version);
		}
	}

	private static final Map<String, TX> TX_IMPL_POOL = new HashMap<String, TX>();

	public static final String key(TX tx) {
		return key(tx.value(), tx.version());
	}

	public static final String key(String code, String version) {
		return code + ":" + version;
	}
}
